fortune = require('./lib/fortune.js')
express = require('express')
formidable = require('formidable') #上传文件解析模块
app = express();
#设置模板引擎
handlebars = require('express3-handlebars').create
  defaultLayout: 'main'
  helpers:
    section: (name, options)->
      if(!this._sections)
        this._sections = {}
      this._sections[name] = options.fn(this)
      return null
app.engine 'handlebars', handlebars.engine
app.set 'view engine', 'handlebars'

#模板缓存
app.set 'view cache', true

#设置视图引擎
app.use express.static(__dirname + '/public')

#中间件 解析URL
app.use require('body-parser')();   #书上说添加了它  req.body才能用
app.get '/newsletter', (req, res)-> #请求newsletter页面，返回Ajax请求，发送下面的/process
  res.render 'newsletter', csrf: 'CSRF token goes here'
app.post '/process', (req, res)->
  # console.log('Form(from querystring)：' + req.query.form)             #打印form名字
  # console.log('CSRF token (from hidden form field):' + req.body._csrf) #打印res.render内的json
  # console.log('Name(from visible form field): ' + req.body.name)       #打印name="name"的value值
  # console.log('Email(from visible form field)：' + req.body.email)     #打印name="email"的value值
  if req.xhr || req.accepts('json, html') is 'json'  #必须是ajax请求才会发送true
    res.send(success: true)
  else                                              #否则重定向到thank-you页面
    res.redirect(303, '/thank-you')  #重定向到/thank-you页面,301有缓存 永久重定向，所以这里用303

#设置端口
app.set 'port', process.env.PORT || 3000

#test=1出现在任何页面查询中
#res.locals.showTests会被设为true
#res.locals对象要传给视图的上下文的一部分
app.use (req, res, next)->
  res.locals.showTests = app.get('env') isnt 'production' and req.query.test is '1'
  next()

#虚拟数据
# mocked weather data
getWeatherData = ()->
  return {
    locations: [
      name: 'Portland',
      forecastUrl: 'http://www.wunderground.com/US/OR/Portland.html',
      iconUrl: 'http://icons-ak.wxug.com/i/c/k/cloudy.gif',
      weather: 'Overcast',
      temp: '54.1 F (12.3 C)',
    ,
      name: 'Bend',
      forecastUrl: 'http://www.wunderground.com/US/OR/Bend.html',
      iconUrl: 'http://icons-ak.wxug.com/i/c/k/partlycloudy.gif',
      weather: 'Partly Cloudy',
      temp: '55.0 F (12.8 C)',
    ,
      name: 'Manzanita',
      forecastUrl: 'http://www.wunderground.com/US/OR/Manzanita.html',
      iconUrl: 'http://icons-ak.wxug.com/i/c/k/rain.gif',
      weather: 'Light Rain',
      temp: '55.0 F (12.8 C)',
    ]}

#天气插件
app.use (req, res, next)->
  if(!res.locals.partials)
    res.locals.partials = {};
  res.locals.partials.weatherContext = getWeatherData();
  next()

# 根目录路由
app.get '/', (req, res)->
  res.render('home');                          #response home页面

#headers页面               请求/headers地址打印出请求头的信息
app.get '/headers', (req, res)->
  res.set('Content-Type', 'text/plain');
  s = '';
  for name in req.headers
    s += name + ': ' + req.headers[name] + '\n'
  res.send(s);

#about页面路由
app.get '/about', (req, res)->
  res.render 'about',
    fortune: fortune.getFortune()
    pageTestScript: '/qa/tests-about.js'

#think-you页面
app.get '/thank-you', (req, res)->
  res.render('thank-you')

#旅游线路页面
app.get '/tours/hood-river', (req, res)->
  res.render('tours/hood-river')
app.get '/tours/request-group-rate', (req, res)->
  res.render('tours/request-group-rate')

#foo测试页面
app.get '/foo', (req, res)->
  res.render('foo', {layout: 'other'})

#段落，视图文件往布局文件head和body加入段落
app.get '/jquerytest', (req, res)->
  res.render('jquerytest')

#nursery-rhyme
app.get '/nursery-rhyme', (req, res)->
  res.render('nursery-rhyme')
app.get '/data/nursery-rhyme', (req, res)->
  res.json
    animal: 'squirrel'
    bodyPart: 'tail'
    adjective: 'bushy'
    noun: 'heck'

#/contest/vacation-photo#文件上传接口
app.get "/contest/vacation-photo", (req,res)->
  now = new Date()
  res.render 'contest/vacation-photo',
    year: now.getFullYear()
    month: now.getMonth()
app.post '/contest/vacation-photo/:year/:mouth', (req, res)->  #year mouth被指定为路由参数
  form = new formidable.IncomingForm()
  form.parse req, (err, fields, files)->
    if err
      console.log 'error'
      return res.redirect 303, '/error'
    console.log 'received fields:'
    console.log fields                       #打印json字符串
    console.log 'received files:'
    console.log files
    res.redirect 303, '/thank-you'

# 404 catch-all处理器（中间件）
app.use (req, res)-> #use处理所有没有路由匹配路径的处理器
  res.status(404)
  res.render('404') #node为res.end

# 500错误处理器（中间件）
app.use (err, req, res, next)->
  console.error(err.stack)
  res.status(500) #res.writeHead
  res.send('500')

#监听端口
app.listen app.get('port'), ()->
  console.log('Express started on http://localhost:' +
    app.get('port') + '; press Ctrl-C to terminate.')